var mongoose = require('mongoose');
var User=require("../model/users");
module.exports={
    list(req,res,next){
        var page=(req.body.page)?req.body.page:1;
        var limit=(req.body.limit)?req.body.limit:2;
        var queyCondition={};
        if(req.body.name&&req.body.name.trim().length>0){
            name=req.body.name;
            queyCondition={
                "name":new RegExp(name,"i")
            }
        }
        User.paginate(queyCondition,{page:page,limit:limit},(error,results)=>{
            if(error){
                console.log(error)
            }
            else{
                res.json(results);
            }
        })
    },
    login(req,res,next){
        console.log(req.body);
        User.findOne(req.body,function(error,result){
            if(error){
                console.log(error)
            }
            else{
                res.json(result);
            }
        })
    },
    post(req,res,next){

        console.log(req.body);
        const user=new User(req.body);
        user.save(function(error,result){
            if(error){
                res.json(error);
            }
            else{
                res.json(result);
            }
        })
    },
    put(req,res,next){
        const id=req.params.id;
        User .findByIdAndUpdate(id,{$set:{name:req.body.name,
            password:req.body.password,
            email:req.body.email,
            age:req.body.age}},{new:false}).then((result)=>{
                    res.json(result);
            })
    },
    delete(req,res,next){
        const id=req.params.id;
        User.findByIdAndRemove(id,function(error,result){
            if(error){
                console.log(error)
            }
            else{
                res.json("delete is ok!")
            } 
           
        })
    },
    deletemany(req,res,next){
        const id=req.body.id;
        User.remove({"_id":{ $in:id}},function(error,result){
            if(error){
                console.log(error)
            }
            else{
                res.json("deletemany is ok!")
            } 
            
        })
    }
}